package src.service;

import src.entity.User;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class UserServiceJsonImpl implements UserService {
    private static final String DATA_DIR = "data";
    private static final String USERS_FILE = DATA_DIR + "/users.json";
    private List<User> users;

    public UserServiceJsonImpl() {
        this.users = loadUsers();
    }

    /**
     * 手动将User对象转换为JSON字符串
     */
    private String userToJson(User user) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        json.append("\"account\":\"").append(escapeJson(user.getAccount())).append("\",");
        json.append("\"password\":\"").append(escapeJson(user.getPassword())).append("\",");
        json.append("\"avatar\":").append(user.getAvatar() == null ? "null" : "\"" + escapeJson(user.getAvatar()) + "\"");
        // 可以继续添加habits, goals, achievements等字段
        json.append("}");
        return json.toString();
    }

    /**
     * 手动解析JSON字符串为User对象
     */
    private User jsonToUser(String jsonStr) {
        try {
            // 简单的JSON解析
            String account = extractJsonValue(jsonStr, "account");
            String password = extractJsonValue(jsonStr, "password");
            String avatar = extractJsonValue(jsonStr, "avatar");

            if ("null".equals(avatar)) {
                avatar = null;
            }

            User user = new User(account, password);
            user.setAvatar(avatar);
            return user;
        } catch (Exception e) {
            System.out.println("JSON解析失败: " + jsonStr);
            return null;
        }
    }

    /**
     * 从JSON字符串中提取字段值
     */
    private String extractJsonValue(String json, String field) {
        String search = "\"" + field + "\":";
        int start = json.indexOf(search);
        if (start == -1) return null;

        start += search.length();
        // 跳过空格
        while (start < json.length() && Character.isWhitespace(json.charAt(start))) {
            start++;
        }

        if (start >= json.length()) return null;

        char firstChar = json.charAt(start);
        if (firstChar == '"') {
            // 字符串值
            start++; // 跳过引号
            int end = json.indexOf('"', start);
            if (end == -1) return null;
            return json.substring(start, end);
        } else if (firstChar == 'n') {
            // null值
            return "null";
        }
        return null;
    }

    /**
     * JSON转义特殊字符
     */
    private String escapeJson(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    /**
     * 加载所有用户从JSON文件
     */
    private List<User> loadUsers() {
        List<User> userList = new ArrayList<>();
        try {
            File file = new File(USERS_FILE);
            if (file.exists()) {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                StringBuilder jsonContent = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonContent.append(line.trim());
                }
                reader.close();

                String content = jsonContent.toString().trim();
                if (content.startsWith("[") && content.endsWith("]")) {
                    // 移除外层的方括号
                    content = content.substring(1, content.length() - 1).trim();

                    // 分割多个JSON对象
                    int braceCount = 0;
                    int start = -1;
                    for (int i = 0; i < content.length(); i++) {
                        char c = content.charAt(i);
                        if (c == '{') {
                            braceCount++;
                            if (start == -1) start = i;
                        } else if (c == '}') {
                            braceCount--;
                            if (braceCount == 0 && start != -1) {
                                String userJson = content.substring(start, i + 1);
                                User user = jsonToUser(userJson);
                                if (user != null) {
                                    userList.add(user);
                                }
                                start = -1;
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("加载用户数据失败: " + e.getMessage());
        }
        return userList;
    }

    /**
     * 保存所有用户到JSON文件
     */
    private void saveUsers() {
        try {
            File dataDir = new File(DATA_DIR);
            if (!dataDir.exists()) {
                dataDir.mkdirs();
            }

            File file = new File(USERS_FILE);
            PrintWriter writer = new PrintWriter(new FileWriter(file));

            writer.println("[");
            for (int i = 0; i < users.size(); i++) {
                writer.print("  " + userToJson(users.get(i)));
                if (i < users.size() - 1) {
                    writer.println(",");
                } else {
                    writer.println();
                }
            }
            writer.println("]");

            writer.close();
            System.out.println("用户数据已保存到JSON文件: " + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println("保存用户数据失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public boolean register(String account, String password) {
        if (getUser(account) != null) {
            return false;
        }

        User newUser = new User(account, password);
        users.add(newUser);
        saveUsers();
        return true;
    }

    @Override
    public boolean login(String account, String password) {
        User user = getUser(account);
        return user != null && user.getPassword().equals(password);
    }

    @Override
    public User getUser(String account) {
        return users.stream()
                .filter(user -> user.getAccount().equals(account))
                .findFirst()
                .orElse(null);
    }

    @Override
    public boolean updatePassword(String account, String oldPwd, String newPwd) {
        User user = getUser(account);
        if (user != null && user.getPassword().equals(oldPwd)) {
            user.setPassword(newPwd);
            saveUsers();
            return true;
        }
        return false;
    }

    @Override
    public boolean updateAvatar(String account, String avatarUrl) {
        User user = getUser(account);
        if (user != null) {
            user.setAvatar(avatarUrl);
            saveUsers();
            return true;
        }
        return false;
    }

    /**
     * 获取所有用户（用于测试）
     */
    public List<User> getAllUsers() {
        return new ArrayList<>(users);
    }
}